package com.zgf.utils;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@Component
public class ConnectionUtils {

    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
   @Resource
    public DataSource dataSource;



    /**
     * 获取当前线程上的连接
     * */
    public Connection getThreadConnecation(){

        try {
            Connection conn = tl.get();
            if (conn == null){
                conn = dataSource.getConnection();
                tl.set(conn);
            }
            return conn;
        }catch (SQLException e) {
          throw new RuntimeException(e);
        }
    }


    /**
     * 把链接和线程解绑
     * */
    public void removeConection(){
        tl.remove();
    }
}
